package handler

import (
	"encoding/json"
	"store-sys/cache"
	"store-sys/models"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Detail(c *gin.Context) {
	id := c.Query("id")
	var store models.Store
	redis_key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).Find(&store)
		jsonData, _ := json.Marshal(store)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &store)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": store,
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var store []models.Store
	redis_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&store)
		jsonData, _ := json.Marshal(store)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &store)
	}
	var total int64
	models.DB.Model(&models.Store{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  store,
		"total": total,
	})
	return
}
func Add(c *gin.Context) {
	store_name := c.PostForm("store_name")
	store_seat := c.PostForm("store_seat")
	foot_traffic := c.PostForm("foot_traffic")
	data := models.Store{
		Model:       gorm.Model{},
		StoreName:   store_name,
		StoreSeat:   store_seat,
		FootTraffic: foot_traffic,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
